<template>
  <div class="preview-wrap">
    <word-file v-if="fileType === 'word'" :loading="loading" :file="fileData"></word-file>
    <excel-file v-else-if="fileType === 'excel'" :loading="loading" :file="fileData"></excel-file>
    <pdf-file v-else-if="fileType === 'pdf'" :loading="loading" :file="fileData"></pdf-file>
  </div>
</template>

<script>
import api from '@/apis/request';
import wordFile from './word-file';
import excelFile from './excel-file';
import pdfFile from './pdf-file';

export default {
  name: 'file-preview',
  components: { wordFile, excelFile, pdfFile },
  props: ['file'],
  data() {
    return {
      loading: false,
      fileData: '',
      fileType: '',
    };
  },
  watch: {
    file: {
      handler(val) {
        if (val) {
          this.getFileBuffer(val.id);
          this.fileType = this.getFileType(val);
        }
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    // word | excel | pdf
    getFileType(file) {
      let fileType = '';
      if (!file) return;

      if (['xls', 'xlsx'].includes(this.file.fileType)) {
        fileType = 'excel';
      } else if (['docx'].includes(this.file.fileType)) {
        fileType = 'word';
      } else {
        fileType = file.fileType;
      }

      return fileType;
    },

    getFileBuffer(fileId) {
      if (!fileId) return;
      let responseType = 'blob';
      if (['excel'].includes(this.fileType)) {
        responseType = 'arraybuffer';
      }

      this.loading = true;
      api.request({
        url: '/file/download?fileId=' + fileId,
        method: 'post',
        responseType,
      }).then(fileData => {
        this.loading = false;
        if (fileData) {
          this.fileData = fileData;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.preview-wrap {
  width: 100%;
  height: 680px;
}
</style>
